package com.platform.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.platform.base.domain.MeterInfo;
import com.platform.base.service.IMeterInfoService;
import com.platform.common.core.text.Convert;
import com.platform.common.manager.AsyncManager;
import com.platform.common.utils.netty.NettyUtil;
import com.platform.common.utils.rabbit.RabbitUtils;
import com.platform.common.utils.redis.RedisRun;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.CountDownLatch;

/**
 * 热表定时调度任务
 *
 * @author platform
 */
@Component("meterTask")
@Slf4j
public class MeterTask {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IMeterInfoService meterInfoService;

    @Autowired
    private RabbitUtils rabbitUtils;

    /**
     * 根据热表id采集热表数据
     * @param calorIds
     */
    public void meterTaskById(String calorIds) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("calorimeter_id", Arrays.asList(Convert.toStrArray(calorIds)));
        List<MeterInfo> meterInfoList = meterInfoService.list(queryWrapper);
        String address = "";
        for(MeterInfo meterInfo : meterInfoList){
            //获取采集器高位
            String cenhigh = meterInfo.getCollectorId().substring(0,2);
            //获取采集器低位
            String cenlow = meterInfo.getCollectorId().substring(2,4);
            //判断通道是否存在
            if(!redisUtil.hHasKey("sys-netty", meterInfo.getCollectorId())){
                log.error("采集器" + meterInfo.getCollectorId() + "已离线");
                continue;
            }

            String add3 = meterInfo.getMeterId().substring(0,2);
            String add4 = meterInfo.getMeterId().substring(2,4);
            String add5 = meterInfo.getMeterId().substring(4,6);
            String add6 = meterInfo.getMeterId().substring(6,8);
            //控制码
            String cont = "01";
            //获取设备厂商编码
            String factory = meterInfo.getFactory().getFactoryCode();
            //计算校验码
            int ll = NettyUtil.get10HexNum(cenhigh)+NettyUtil.get10HexNum(cenlow)+NettyUtil.get10HexNum(add3)+NettyUtil.get10HexNum(add4)+NettyUtil.get10HexNum(add5)+NettyUtil.get10HexNum(add6)+NettyUtil.get10HexNum(cont)+NettyUtil.get10HexNum(factory);
            String check = NettyUtil.get16HexNum(ll);
            if(check.length()<2){
                check = "0" + check;
            }else{
                check = check.substring(check.length()-2);
            }
            String response = "AA "+ cenlow +" "+ cenhigh + " " + add3 + " " + add4 + " " + add5 + " " + add6 + " " + cont + " " + factory + " 00 00 00 00 00 " + check + " FF ";
            String revertStr = response.replace(" ", "");
            rabbitUtils.writeToClient(meterInfo.getCollectorId(), revertStr, "热表"+meterInfo.getMeterId()+"读取数据");
            address = add3+add4+add5+add6;

            CountDownLatch countDownLatch = new CountDownLatch(1);
            new Thread(new RedisRun(countDownLatch, redisUtil, address, cont)).start();
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 采集所有热表数据
     * @throws ParseException
     */
    public void meterTask() {
        List<MeterInfo> meterInfoList = meterInfoService.list();
        String address = "";
        for(MeterInfo meterInfo : meterInfoList){
            //获取采集器高位
            String cenhigh = meterInfo.getCollectorId().substring(0,2);
            //获取采集器低位
            String cenlow = meterInfo.getCollectorId().substring(2,4);
            //判断通道是否存在
            if(!redisUtil.hHasKey("sys-netty", meterInfo.getCollectorId())){
                log.error("采集器" + meterInfo.getCollectorId() + "已离线");
                continue;
            }

            String add3 = meterInfo.getMeterId().substring(0,2);
            String add4 = meterInfo.getMeterId().substring(2,4);
            String add5 = meterInfo.getMeterId().substring(4,6);
            String add6 = meterInfo.getMeterId().substring(6,8);
            //控制码
            String cont = "01";
            //获取设备厂商编码
            String factory = meterInfo.getFactory().getFactoryCode();
            //计算校验码
            int ll = NettyUtil.get10HexNum(cenhigh)+NettyUtil.get10HexNum(cenlow)+NettyUtil.get10HexNum(add3)+NettyUtil.get10HexNum(add4)+NettyUtil.get10HexNum(add5)+NettyUtil.get10HexNum(add6)+NettyUtil.get10HexNum(cont)+NettyUtil.get10HexNum(factory);
            String check = NettyUtil.get16HexNum(ll);
            if(check.length()<2){
                check = "0" + check;
            }else{
                check = check.substring(check.length()-2);
            }
            String response = "AA "+ cenlow +" "+ cenhigh + " " + add3 + " " + add4 + " " + add5 + " " + add6 + " " + cont + " " + factory + " 00 00 00 00 00 " + check + " FF ";
            String revertStr = response.replace(" ", "");
            rabbitUtils.writeToClient(meterInfo.getCollectorId(), revertStr, "热表"+meterInfo.getMeterId()+"读取数据");
            address = add3+add4+add5+add6;

            CountDownLatch countDownLatch = new CountDownLatch(1);
            new Thread(new RedisRun(countDownLatch, redisUtil, address, cont)).start();
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 采集失败热表数据
     * @throws ParseException
     */
    public void metersTask() {
        List<MeterInfo> collectorList = meterInfoService.selectCollectorInfoEq();
        for(MeterInfo colectorInfo : collectorList){
            AsyncManager.me().execute(checkMeter(colectorInfo.getCollectorId()));
        }
    }

    public static TimerTask checkMeter(String collectorId){

        RedisUtil redisUtil = SpringUtils.getBean(RedisUtil.class);

        RabbitUtils rabbitUtils = SpringUtils.getBean(RabbitUtils.class);

        return new TimerTask() {
            @Override
            public void run() {
                List<MeterInfo> meterInfoList = SpringUtils.getBean(IMeterInfoService.class).selectMeterInfoEq(collectorId);
                String address = "";
                for(MeterInfo meterInfo : meterInfoList){
                    //获取采集器高位
                    String cenhigh = meterInfo.getCollectorId().substring(0,2);
                    //获取采集器低位
                    String cenlow = meterInfo.getCollectorId().substring(2,4);
                    //判断通道是否存在
                    if(!redisUtil.hHasKey("sys-netty", meterInfo.getCollectorId())){
                        log.error("采集器" + meterInfo.getCollectorId() + "已离线");
                        continue;
                    }

                    String add3 = meterInfo.getMeterId().substring(0,2);
                    String add4 = meterInfo.getMeterId().substring(2,4);
                    String add5 = meterInfo.getMeterId().substring(4,6);
                    String add6 = meterInfo.getMeterId().substring(6,8);
                    //控制码
                    String cont = "01";
                    //获取设备厂商编码
                    String factory = meterInfo.getFactory().getFactoryCode();
                    //计算校验码
                    int ll = NettyUtil.get10HexNum(cenhigh)+NettyUtil.get10HexNum(cenlow)+NettyUtil.get10HexNum(add3)+NettyUtil.get10HexNum(add4)+NettyUtil.get10HexNum(add5)+NettyUtil.get10HexNum(add6)+NettyUtil.get10HexNum(cont)+NettyUtil.get10HexNum(factory);
                    String check = NettyUtil.get16HexNum(ll);
                    if(check.length()<2){
                        check = "0" + check;
                    }else{
                        check = check.substring(check.length()-2);
                    }
                    String response = "AA "+ cenlow +" "+ cenhigh + " " + add3 + " " + add4 + " " + add5 + " " + add6 + " " + cont + " " + factory + " 00 00 00 00 00 " + check + " FF ";
                    String revertStr = response.replace(" ", "");
                    rabbitUtils.writeToClient(meterInfo.getCollectorId(), revertStr, "热表"+meterInfo.getMeterId()+"读取数据");
                    address = add3+add4+add5+add6;

                    CountDownLatch countDownLatch = new CountDownLatch(1);
                    new Thread(new RedisRun(countDownLatch, redisUtil, address, cont)).start();
                    try {
                        countDownLatch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }
}
